from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from kubernetes import config, client

# Create your views here.

# 加载 Kubernetes 配置
config.load_kube_config()

# 获取API的CoreV1Api版本对象
v1 = client.CoreV1Api()


# 列出所有容器
@csrf_exempt
def container_ls(request):
    if request.method == 'GET':
        try:
            pod_list = v1.list_namespaced_pod('default')
            container_list = []
            if container_list is None:
                return JsonResponse({'status': 200, 'msg': '容器列表获取成功', 'data': container_list})
            for container in pod_list.items:
                dic = {
                    'container_name': container.spec.containers[0].name,
                    'container_image': container.spec.containers[0].image,
                    'container_status': container.status.phase,
                    'create_time': container.metadata.creation_timestamp,
                    'container_id': container.status.container_statuses[0].container_id,
                    'container_ip': container.status.pod_ip,
                    'container_node': container.spec.node_name,
                    'container_port': container.spec.containers[0].ports[0].container_port,
                    'container_host_ip': container.status.host_ip
                }
                container_list.append(dic)
        except Exception as e:
            print(e)
            return JsonResponse({'status': 400, 'msg': '容器列表获取失败'})
        return JsonResponse({'status': 200, 'msg': '容器列表获取成功', 'data': container_list})
    else:
        return JsonResponse({'status': 400, 'msg': '请求方式错误'})
    pass


# 创建容器
@csrf_exempt
def container_create(request):
    if request.method == 'POST':
        image_name = request.POST.get('image_name')
        container_name = request.POST.get('container_name')
        container_port = request.POST.get('container_port')
        image_tag = request.POST.get('image_tag')
        if image_tag is None:
            image_tag = 'latest'
        print(image_name, image_tag, container_name, container_port)
        try:
            pod = v1.list_pod_for_all_namespaces(watch=False)
            for i in pod.items:
                if i.spec.containers[0].name == container_name:
                    return JsonResponse({'status': 400, 'msg': '容器创建失败，容器名已存在'})
            v1.create_namespaced_pod(body={
                "apiVersion": "v1",
                "kind": "Pod",
                "metadata": {
                    "name": container_name
                },
                "spec": {
                    "containers": [
                        {
                            "name": container_name,
                            "image": image_name + ':' + image_tag,
                            "ports": [
                                {
                                    "containerPort": int(container_port)
                                }
                            ]
                        }
                    ]
                }
            }, namespace='default')
        except Exception as e:
            print(e)
            return JsonResponse({'status': 400, 'msg': '容器创建失败'})
        return JsonResponse({'status': 200, 'msg': '容器创建成功'})
    else:
        return JsonResponse({'status': 400, 'msg': '请求方式错误'})
    pass


# 删除容器
@csrf_exempt
def container_rm(request):
    if request.method == 'POST':
        container_name = request.POST.get('container_name')
        try:
            v1.delete_namespaced_pod(name=container_name, namespace='default')
        except Exception as e:
            print(e)
            return JsonResponse({'status': 400, 'msg': '容器删除失败'})
        return JsonResponse({'status': 200, 'msg': '容器删除成功'})
    else:
        return JsonResponse({'status': 400, 'msg': '请求方式错误'})
    pass
